//
//  ViewController.m
//  OCJavaScript
//
//  Created by xiaerfei on 2019/7/30.
//  Copyright © 2019 xiaerfei. All rights reserved.
//

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "VView.h"
#import "VLabel.h"

@interface ViewController ()
@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) JSVirtualMachine *vm;
@property (nonatomic, strong) JSContext *context;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.queue = dispatch_queue_create("label", NULL);
    __weak typeof(self) _self = self;
    dispatch_sync(self.queue, ^{
        _self.vm = [[JSVirtualMachine alloc] init];
    });
    
    self.context = [[JSContext alloc] initWithVirtualMachine:self.vm];
    self.context[@"View"] = ^() {
        return  VView.new;
    };
    self.context[@"Image"] = ^() {
        return  UIImageView.new;
    };
    self.context[@"Label"] = ^() {
        return  VLabel.new;
    };
    
    [self registerJS:@"app" type:@"js"];
    
    JSValue *v = [self.context objectForKeyedSubscript:@"createView"];
    JSValue *ret = [v callWithArguments:@[@"111111"]];
    VView *vv = ret.toObject;
    vv.frame = self.view.frame;
    [self.view addSubview:vv];
    NSLog(@"%@",ret.toObject);
}

- (void)registerJS:(NSString *)src type:(NSString *)type {
    NSString *path = [[NSBundle mainBundle] pathForResource:src ofType:type];
    NSString *jsStr = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
    [self.context evaluateScript:jsStr];
}



@end
